const path = require('path');
const fs = require('fs');
const express = require('express');
const router = express.Router();
const { CODE } = require('../utils/constants')
// 引入user模型
const userModel = require('../db/model/userModel')
// 导入formidable
const formidable = require('formidable');
// 用户分页列表接口 page 当前页 limit 每页显示几条

// 导入upload工具函数
const uploadUtils = require('../utils/uploadUtils')
const md5 = require('../utils/md5')
router.get('/user/:page/:limit', async (req, res) => {
    /**
     *  总条数： totalNum
     *  总页数：totalPage = Math.ceil(totalNum/limit)
     *  skipNum = (page - 1) * limit 
     */
    let { page, limit } = req.params;
    try {
        let totalNum = await userModel.count({}); // 获取所有用户的条数
        // console.log(totalNum);
        let totalPage = Math.ceil(totalNum / limit)
        // console.log('totalPage: ', totalPage);
        let skipNum = (page - 1) * limit;
        // console.log('skipNum: ', skipNum);
        // 获取用户分页列表数据
        let users = await userModel.find({}).skip(skipNum).limit(limit).select({ pwd: 0 })
        console.log('users: ', users);
        res.json({
            code: CODE.SUCCESS,
            data: {
                users,
                totalPage
            },
            message: '获取分页列表成功'
        })
    } catch (e) {
        res.json({
            code: CODE.SERVER_ERROR,
            data: null,
            message: '网络链接异常'
        })
    }
})

// 添加用户路由  username pwd  头像图片
router.post('/user', async (req, res) => {
    try {
        let fields = await uploadUtils(req, 'profileFile');
        console.log('fields upload: ', fields);
        // 加密密码
        fields.pwd = md5(fields.pwd);
        let user = await userModel.create(fields)
        let responseData = {
            _id: user._id,
            username: user.username,
            profile: user.profile,
            create_time: user.create_time
        }
        res.json({
            code: CODE.SUCCESS,
            data: responseData,
            message: '用户添加成功'
        })

    } catch (e) {
        res.json({
            code: CODE.SERVER_ERROR,
            data: null,
            message: '未上传用户头像'
        })
    }
})
// 根据query参数_id 查询用户数据
// localhost:9999/admin/user?id=xxjklej123
router.get('/user', async (req, res) => {
    // 1.获取id
    let { id } = req.query;
    try {
        let user = await userModel.findOne({ _id: id })
        res.json({
            code: CODE.SUCCESS,
            data: user,
            message: '获取用户数据成功'
        })
    } catch (e) {
        res.json({
            code: CODE.SERVER_ERROR,
            data: null,
            message: '网络链接异常'
        })
    }
})
// 根据id更新用户信息
router.put('/user', async (req, res) => {
    let fields = await uploadUtils(req, 'profileFile');
    console.log('fields123123: ', fields);
    let {_id, username, profile} = fields;
    try {
        // 根据_id 更新数据库
        await userModel.updateOne({ _id }, { username, profile })
        res.json({
            code: CODE.SUCCESS,
            message: '更新成功'
        })
    } catch (e) {
        res.json({
            code: CODE.SERVER_ERROR,
            data: null,
            message: '网络链接异常'
        })
    }
})

// 根据id删除用户 
// 1. 删除用户的图片
// 2. 删除数据库信息
router.delete('/user/:id', async (req, res)=>{
    let {id} = req.params;
    try{
        // 根据id获取图片路径，删除用户的头像图片
        let user = await userModel.findOne({_id:id});
        let avatarPath = path.resolve(__dirname,'../public') + user.profile;
        console.log('avatarPath: ', avatarPath);
        fs.unlinkSync(avatarPath)
        await userModel.deleteOne({_id:id})
        res.json({
            code:CODE.SUCCESS,
            data:null,
            message:'用户删除成功'
        })
    }catch(e){
        res.json({
            code:CODE.SERVER_ERROR,
            message:'网络链接异常'
        })
    }
})

module.exports = router;